package com.hoshiicloud.commissioncalculation.job;

import com.hoshiicloud.commissioncalculation.entity.TradeFlow;
import com.hoshiicloud.commissioncalculation.feign.GoodsFeignService;
import com.hoshiicloud.commissioncalculation.feign.IdGeneratorService;
import com.hoshiicloud.commissioncalculation.feign.OrderFeignService;
import com.hoshiicloud.commissioncalculation.feign.UserFeignService;
import com.hoshiicloud.commissioncalculation.service.TradeFlowService;
import com.hoshiicloud.common.feign.BaseIdGeneratorService;
import com.hoshiicloud.common.rpc.Response;
import com.hoshiicloud.goods.entity.sku.ExtSku;
import com.hoshiicloud.saleorder.dto.PlatStoreDTO;
import com.hoshiicloud.saleorder.entity.OrderInfo;
import com.hoshiicloud.saleorder.entity.OrderMain;
import com.hoshiicloud.saleorder.param.OrderInfoQueryParam;
import com.hoshiicloud.saleorder.param.OrderMainQueryParam;
import com.hoshiicloud.user.entity.store.PlatStore;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.IJobHandler;
import com.xxl.job.core.handler.annotation.JobHandler;
import com.xxl.job.core.log.XxlJobLogger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * @author ygd
 * @title: CommissionJobHandler
 * @projectName hoshiicloud
 * @description: 分佣任务
 * @date 2019/9/5
 */
@Component
@JobHandler("commissionJobHandler")
public class CommissionJobHandler extends IJobHandler {

    @Autowired
    private OrderFeignService orderFeignService;

    @Autowired
    private GoodsFeignService goodsFeignService;

    @Autowired
    private UserFeignService userFeignService;

    @Autowired
    private TradeFlowService tradeFlowService;

    @Autowired
    private BaseIdGeneratorService baseIdGeneratorService;

    private DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");


    @Override
    public ReturnT<String> execute(String s) {
        try {
            //查询已归档订单
            OrderMainQueryParam param = OrderMainQueryParam.builder().orderStatus(10).build();

            Response<List<OrderMain>> response = orderFeignService.queryOrderMainList(param);

            if (response != null && response.getData() != null) {

                List<OrderMain> orderMainList = response.getData();

                List<PlatStore> platStoreList = new ArrayList<>();
                List<TradeFlow> tradeFlowList = new ArrayList<>();

                Set<String> idSet = baseIdGeneratorService.queryGeneratorIds(orderMainList.size());
                Iterator<String> it = idSet.iterator();
                for (OrderMain orderMain : orderMainList) {

                    //店铺分佣总金额
                    BigDecimal commissionAmountSum = BigDecimal.ZERO;

                    List<Long> mainIds = new ArrayList<>();
                    mainIds.add(orderMain.getId());
                    //计算店铺分佣金额
                    commissionAmountSum = this.storeCommissionAmount(mainIds);

                    PlatStore platStore = this.setPlatStore(orderMain.getStoreId(), commissionAmountSum);
                    platStoreList.add(platStore);

                    Long transFlowId = Long.valueOf(it.next());
                    TradeFlow tradeFlow = TradeFlow.builder()
                            .id(transFlowId)
                            .companyid(orderMain.getCompanyId())
                            .platformid(orderMain.getPlatformId())
                            .txdate(new Date())
                            .txtype(4)
                            .project("佣金结算")
                            .orderNo(LocalDateTime.now().format(formatter) + transFlowId)
                            .amount(commissionAmountSum)
                            .transfelInAccType(3)
                            .transfelInAccId(orderMain.getStoreId())
                            .transfelInType(1)
                            .transfelInAccBanance(platStore.getAvailableBalance())
                            .transfelOutAccType(4)
                            .transfelOutAccId(orderMain.getPlatformId())
                            .transfelOutType(1)
                            .transfelOutAccBanance(BigDecimal.ZERO)
                            .status(1)
                            .orderId(orderMain.getId())
                            .createdtime(new Date())
                            .createdby("system").build();

                    tradeFlowList.add(tradeFlow);
                }

                //更新店铺账户
                updateBatchPlatStore(platStoreList);

                //批量新增流水
                saveBatchTradeFlow(tradeFlowList);

            }


        } catch (Exception e) {
            XxlJobLogger.log("分佣任务异常：", e);

        }
        return SUCCESS;
    }


    /**
     * 店铺分佣金额
     *
     * @param mainIds
     * @return
     */
    public BigDecimal storeCommissionAmount(List<Long> mainIds) throws Exception {

        //店铺分佣总金额
        BigDecimal commissionAmountSum = BigDecimal.ZERO;

        //根据主订单id查询子订单
        OrderInfoQueryParam orderInfoQueryParam = OrderInfoQueryParam.builder().orderStatus(1).mainId(mainIds).build();
        Response<List<OrderInfo>> orderInfoResponse = orderFeignService.queryOrderInfoList(orderInfoQueryParam);

        if (orderInfoResponse != null && orderInfoResponse.getData() != null) {
            List<OrderInfo> orderInfoList = orderInfoResponse.getData();

            for (OrderInfo orderInfo : orderInfoList) {
                //查询商品sku
                Response<ExtSku> extSkuResponse = goodsFeignService.getSkuById(orderInfo.getSkuId());
                ExtSku extSku = extSkuResponse.getData();
                //成本价
                BigDecimal costPrice = extSku.getCostPrice();
                //销售价
                BigDecimal saleprice = orderInfo.getSaleUnitPrice();
                //数量
                BigDecimal quantity = new BigDecimal(orderInfo.getQuantity());

                //店铺分佣金额  (销售价-成本价)*数量
                BigDecimal commissionAmount = BigDecimal.ZERO;
                if (saleprice.compareTo(costPrice) > 0) {

                    commissionAmount = (saleprice.subtract(costPrice)).multiply(quantity);

                }
                commissionAmountSum = commissionAmountSum.add(commissionAmount);
            }
        }
        return commissionAmountSum;
    }


    /**
     * 批量更新店铺账户信息
     *
     * @param platStoreList
     */
    public void updateBatchPlatStore(List<PlatStore> platStoreList) throws Exception {
        userFeignService.updateBatchStores(platStoreList);
    }

    /**
     * 批量新增流水
     *
     * @param tradeFlowList
     * @throws Exception
     */
    public void saveBatchTradeFlow(List<TradeFlow> tradeFlowList) throws Exception {
        tradeFlowService.saveBatch(tradeFlowList, tradeFlowList.size());
    }

    /**
     * @param storeId
     * @param commissionAmountSum
     * @return
     */
    public PlatStore setPlatStore(Long storeId, BigDecimal commissionAmountSum) throws Exception {

        //查询店铺信息
        Response<PlatStoreDTO> platStoreDTOResponse = userFeignService.queryById(storeId);

        PlatStoreDTO platStoreDTO = platStoreDTOResponse.getData();

        return PlatStore.builder()
                .id(storeId)
                .accountBalance(platStoreDTO.getAccountBalance().add(commissionAmountSum))
                .availableBalance(platStoreDTO.getAvailableBalance().add(commissionAmountSum))
                .build();
    }
}
